﻿using System;
using System.Web;
using Microsoft.SharePoint;
using SpImageCasheSDK;

namespace SpImageCacheHttpModule
{
    public class SpImageCacheHttpModule : IHttpModule
    {
        private const string SpImagecacheLibraryName = "imagecache";

        private static void EnsureFolders(SPList spList, string folderUrl)
        {
            SPFolder spFolder = spList.ParentWeb.GetFolder(spList.RootFolder.Url + "/" + folderUrl);

            if (!spFolder.Exists)
            {
                string[] folders = folderUrl.Trim('/').Split('/');

                string folderPath = string.Empty;

                foreach (string folderName in folders)
                {
                    folderPath += "/" + folderName;

                    spFolder = spList.ParentWeb.GetFolder(spList.RootFolder.Url + folderPath);

                    if (!spFolder.Exists)
                    {
                        SPListItem newFolder = spList.Items.Add("", SPFileSystemObjectType.Folder, folderPath.Trim('/'));

                        newFolder.Update();
                    }
                }
            }
        }

        private static void CreatePresetImage(SpImageCacheData spImageCacheData)
        {
            SPWeb spWeb = SPContext.Current.Web;

            SPFile spFileOriginal = spWeb.GetFile(spImageCacheData.OriginalFilePath);

            if (spFileOriginal.Exists)
            {
                SPFile spFileImageCache = spWeb.GetFile(spImageCacheData.ImageCacheFilePath);

                if (!spFileImageCache.Exists || (spFileOriginal.Item["Modified"] != null && spFileImageCache.Item["OrigModified"] != null && DateTime.Compare((DateTime)spFileOriginal.Item["Modified"], (DateTime)spFileImageCache.Item["OrigModified"]) != 0))
                {
                    spWeb.AllowUnsafeUpdates = true;

                    EnsureFolders(spWeb.Lists[SpImageCacheData.SpImagecacheLibraryName], string.Format("{0}/{1}/{2}", spImageCacheData.PresetName, spImageCacheData.OriginalLibraryName, spImageCacheData.RelativeFoldersPath));

                    spFileOriginal.CopyTo(spImageCacheData.ImageCacheFilePath, true);

                    spWeb.AllowUnsafeUpdates = false;
                }
            }
        }

        private static void SpImageCacheRequest(object sender, EventArgs eventArgs)
        {
            HttpApplication httpApplication = (HttpApplication)sender;

            if (httpApplication.Request.Path.Contains(SpImagecacheLibraryName) && !httpApplication.Request.Path.Contains("/_t/") && !httpApplication.Request.Path.Contains("/_w/"))
            {
                SpImageCacheData spImageCacheData = new SpImageCacheData(httpApplication.Request.Path);

                if (!string.IsNullOrEmpty(SpImageCacheData.SpImagecacheLibraryName) && !string.IsNullOrEmpty(spImageCacheData.PresetName) &&
                    !string.IsNullOrEmpty(spImageCacheData.OriginalLibraryName) && !string.IsNullOrEmpty(spImageCacheData.RelativeFilePath))
                {

                    CreatePresetImage(spImageCacheData);
                }
            }
        }

        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += SpImageCacheRequest;
        }

        public void Dispose()
        {
        }
    }
}
